import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { Box, LegacyCard, Text, VerticalStack } from '@shopify/polaris';
import { coy } from 'react-syntax-highlighter/dist/esm/styles/prism';
import func from '@/util/func';
import transform from '../../../components/shared/customDiffEditor';
import { MarkdownRenderer, markdownStyles } from '@/apps/dashboard/components/shared/MarkdownComponents';

const HttpRequestResponseViewer = ({ data, viewMode = 'syntax' }) => {
  
  const requestJsonObj = func.requestJson(data, [])
  const responseJsonObj = func.responseJson(data, [])

  const formattedRequest = transform.formatData(requestJsonObj,"http")
  const formattedResponse = transform.formatData(responseJsonObj,"http")

  const MAX_CHARACTERS = 15_000

  const truncateContent = (content) => {
    return content.length > MAX_CHARACTERS ? content.slice(0, MAX_CHARACTERS) + '...\n' : content
  }

  const formatAsMarkdownCodeBlock = (content) => {
    return `\`\`\`http\n${truncateContent(content)}\n\`\`\``
  }

  const renderContent = (content, title) => {
    if (viewMode === 'markdown') {
      return (
        <Box>
          <LegacyCard>
            <Box padding={3} borderRadius='2'>
              <Text>{title}</Text>
              <Box style={{maxHeight: '4000px', overflowY: 'auto'}}>
                <div className="markdown-content">
                  <MarkdownRenderer>
                    {formatAsMarkdownCodeBlock(content)}
                  </MarkdownRenderer>
                </div>
              </Box>
            </Box>
          </LegacyCard>
        </Box>
      )
    }

    return (
      <Box>
        <LegacyCard>
          <Box padding={3} borderRadius='2'>
            <Text>{title}</Text>
            <Box style={{maxHeight: '4000px', overflowY: 'hidden'}} overflowY='hidden'>
              <SyntaxHighlighter lineProps={{style: {whiteSpace: 'pre-wrap', wordBreak: 'break-all', display: 'block'}}} wrapLongLines={true} showLineNumbers={true} language="http" style={coy}>
                {truncateContent(content)}
              </SyntaxHighlighter>
            </Box>
          </Box>
        </LegacyCard>
      </Box>
    )
  }
  
  return (
    <VerticalStack gap={3}>
      {renderContent(formattedRequest, 'Request')}
      {renderContent(formattedResponse, 'Response')}
      {viewMode === 'markdown' && (
        <style jsx>{`
          ${markdownStyles}
        `}</style>
      )}
    </VerticalStack>
  )
}

export default HttpRequestResponseViewer
